import json
import os
import ast
import random

from django.http import JsonResponse
from django.http import FileResponse
from django.shortcuts import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from . import random_graph

from py2neo import Graph


# def hello(request):
#     # return HttpResponse('<div style="color:dodgerblue;background-color:aqua;">Ernestgg</div>')
#     return render(request, "tmpl1.html", {"divText": "ERNEST'S FIRST DIV TEXT","divData":False})


def zstp_handler(request):
    is_random = 1

    if is_random:
        random_graph_json_dict = \
            random_graph.generate_random_graph(request.GET["entityName"], 99, 100)

        print(
            f"[Info] ZSTP Handler: Generated {len(random_graph_json_dict['nodes'])} nodes "
            f"and {len(random_graph_json_dict['edges'])} edges "
            f"for entityName \"{request.GET['entityName']}\"")
        return JsonResponse(random_graph_json_dict)

    return JsonResponse({"nodes": [
        {"id": 0, "label": "复方丹参片(茂祥)[国药准字Z22022832]..药品", "group": "0"},
        {"id": 1, "label": "(MaoXiang)FuFangDanCanPian..药品", "group": "1"},
        {"id": 2, "label": "密封..贮藏条件", "group": "1"},
        {"id": 3, "label": "茂祥集团吉林制药有限公司..企业", "group": "1"},
        {"id": 4, "label": "冰片..药物", "group": "1"},
        {"id": 5, "label": "丹参..药物", "group": "1"},
        {"id": 6, "label": "三七..药物", "group": "1"},
        {"id": 7, "label": "处方药物..处方状态", "group": "1"},
        {"id": 8, "label": "国家医保目录（甲类）..医疗保险类别划分", "group": "1"},
        {"id": 9, "label": "国家基本药物目录（2012）..医保地区", "group": "1"},
        {"id": 10, "label": "茂祥..药品", "group": "1"},
        {"id": 11, "label": "复方丹参片..药品", "group": "1"},
        {"id": 12, "label": "药品..药品", "group": "1"},
        {"id": 13, "label": "中西药..药品", "group": "1"}],
        "edges": [{"from": 0, "to": 1, "label": "药品\\英文名\\药品"},
                  {"from": 0, "to": 2, "label": "药品\\有贮藏条件\\贮藏条件"},
                  {"from": 0, "to": 3, "label": "药品\\有生产企业\\企业"},
                  {"from": 0, "to": 4, "label": "药品\\有成分\\药物"},
                  {"from": 0, "to": 5, "label": "药品\\有成分\\药物"},
                  {"from": 0, "to": 6, "label": "药品\\有成分\\药物"},
                  {"from": 0, "to": 7, "label": "药品\\有处方状态\\处方状态"},
                  {"from": 0, "to": 8, "label": "药品\\有医保类别\\医疗保险类别划分"},
                  {"from": 0, "to": 9, "label": "药品\\有医保地区\\医保地区"},
                  {"from": 0, "to": 10, "label": "药品\\别名\\药品"},
                  {"from": 0, "to": 11, "label": "药品\\别名\\药品"},
                  {"from": 0, "to": 12, "label": "药品\\subClassOf\\药品"},
                  {"from": 0, "to": 13, "label": "药品\\subClassOf\\药品"}]})


def zstp_route_handler(request):
    is_random = 1

    if is_random:
        random_graph_json_dict = \
            random_graph.generate_random_route(request.GET["from"], request.GET["to"], 20,
                                               40)

        print(
            f"[Info] ZSTP Handler: Generated {len(random_graph_json_dict['nodes'])} nodes "
            f"and {len(random_graph_json_dict['edges'])} edges "
            f"from \"{request.GET['from']}\" to \"{request.GET['to']}\"")

        return JsonResponse(random_graph_json_dict)

    return JsonResponse({"nodes": [
        {"id": 0, "label": "呕吐..疾病", "group": "0", "type": "疾病",
         "properties": [{"name": "是否医保", "text": " 是"},
                        {"name": "有ICD", "text": "R11xx01"}]},
        {"id": 1, "label": "当归南枣胶囊[国药准字Z20060250]..药品", "group": "1", "type": "药品",
         "properties": [{"name": "性状", "text": "本品为硬胶囊，内容物为黄棕色至棕色的颗粒和粉末；气香，味辛。"},
                        {"name": "有批准文号", "text": "国药准字Z20060250"},
                        {"name": "有有效期", "text": "24月"},
                        {"name": "有用法用量", "text": "口服，一次3-6片，一日2次。"},
                        {"name": "有规格", "text": "每粒装0.4g"},
                        {"name": "注意事项", "text": "请遵医嘱。"}]},
        {"id": 2, "label": "药品..药品", "group": "1"}], "edges": [
        {"from": 0, "to": 1, "label": "疾病\\可被治疗\\药品", "type": "", "properties": []},
        {"from": 1, "to": 2, "label": "药品\\subClassOf\\药品", "type": "",
         "properties": []}]})


@csrf_exempt
def jbzd_handler_a(request):
    request_data_dict = ast.literal_eval(request.body.decode("utf-8"))

    print(request_data_dict)

    diseases = [
        {
            "disease": "肩周炎",
            "confidence": random.random(),
            "source": "DDGNN"
        },
        {
            "disease": "克雷伯肺炎杆菌脑膜炎",
            "confidence": 0.75,
            "source": "DDGNN"
        },
        {
            "disease": "腰椎间盘突出",
            "confidence": random.random(),
            "source": "DDGNN"
        },
        {
            "disease": "腰椎间盘突出2",
            "confidence": -1,
            "source": "DDGNN"
        },
        {
            "disease": "肩周炎",
            "confidence": random.random(),
            "source": "DDGNN"
        },
        {
            "disease": "克雷伯肺炎杆菌脑膜炎",
            "confidence": 0.75,
            "source": "DDGNN"
        },
        {
            "disease": "腰椎间盘突出",
            "confidence": random.random(),
            "source": "DDGNN"
        },
        {
            "disease": "肩周炎",
            "confidence": random.random(),
            "source": "DDGNN"
        },
        {
            "disease": "克雷伯肺炎杆菌脑膜炎",
            "confidence": 0.75,
            "source": "DDGNN"
        },
        {
            "disease": "腰椎间盘突出",
            "confidence": random.random(),
            "source": "DDGNN"
        },
        {
            "disease": "肩周炎",
            "confidence": random.random(),
            "source": "DDGNN"
        },
        {
            "disease": "克雷伯肺炎杆菌脑膜炎",
            "confidence": 0.75,
            "source": "DDGNN"
        },
        {
            "disease": "腰椎间盘突出",
            "confidence": random.random(),
            "source": "DDGNN"
        }
    ]

    return JsonResponse({'data': diseases})


@csrf_exempt
def jbzd_handler_b(request):
    request_data_dict = ast.literal_eval(request.body.decode("utf-8"))

    print(request_data_dict)

    diseases = [
        {
            "disease": "直男癌",
            "confidence": random.random(),
            "source": "EMR"
        },
        {
            "disease": "新冠",
            "confidence": random.random(),
            "source": "EMR"
        }
    ]

    return JsonResponse({'data': diseases})


@csrf_exempt
def stsb_handler(request):
    sentence = request.GET["sentence"]

    if len(sentence) < 5:
        return JsonResponse({"data": []})

    return JsonResponse({"data": [
        {
            "entity": sentence[0:2],
            "type": "TYPE IS Alpha"
        },
        {
            "entity": sentence[3:5],
            "type": "TYPE IS Bravo"
        }
    ]})


@csrf_exempt
def login_handler(request):
    request_data_dict = ast.literal_eval(request.body.decode("utf-8"))

    print(request_data_dict)

    print(request.COOKIES)

    if request_data_dict["sessionId"] != "":
        return JsonResponse({
            "success": True,
            "level": 10,
            "sessionId": ""
        })
    else:
        return JsonResponse({
            "success": request_data_dict["account"] == "admin"
                       and request_data_dict[
                           "passwordHashed"] == "7RxNFTkfJORFcj1J07mjUcgL/9+yyokjCUU8XiG8uBk=",
            "level": 1,
            # disable auto-login currently
            "sessionId": ""
        })


@csrf_exempt
def logout_handler(request):
    return JsonResponse({})


@csrf_exempt
def entity_relation_op_handler(request):
    request_data_dict = ast.literal_eval(request.body.decode("utf-8"))

    print(request_data_dict)

    return JsonResponse({"success": True})


@csrf_exempt
def query_entity_handler(request):
    return JsonResponse({"label": "当归南枣胶囊[国药准字Z20060250]..药品", "type": "药品",
                         "properties": [
                             {"name": "性状", "text": "本品为硬胶囊，内容物为黄棕色至棕色的颗粒和粉末；气香，味辛。"},
                             {"name": "有批准文号", "text": "国药准字Z20060250"},
                             {"name": "有有效期", "text": "24月"},
                             {"name": "有用法用量", "text": "口服，一次3-6片，一日2次。"},
                             {"name": "有规格", "text": "每粒装0.4g"},
                             {"name": "注意事项", "text": "请遵医嘱。"}]})


def download_handler(request):
    if request.GET["format"] == "csv":
        csv_file = open("./download_files/asd.csv", "rb")
        response = FileResponse(csv_file, as_attachment=True)
        response["Content-Type"] = "application/octet-stream"
        return response
    else:
        txt_file = open("./download_files/tkk.txt", "rb")
        response = FileResponse(txt_file, as_attachment=True)
        response["Content-Type"] = "application/octet-stream"
        return response


@csrf_exempt
def import_handler(request):
    request_data_dict = ast.literal_eval(request.body.decode("utf-8"))

    print(request_data_dict)

    return JsonResponse({"success": True})